class SqlHistoryController < ApplicationController
  def details
    if current_user.can_audited?
      @sql_order_detail = SqlOrder.all.order(created_at: :desc).where("id=?",params[:id])
    else
      @sql_order_detail = SqlOrder.all.where("user_id=?",current_user.id).where("id=?",params[:id]).order(created_at: :desc)
    end
  end

  def index
    if current_user.can_audited?
      @sql_order_his = SqlOrder.all.where("created_at >= current_date-7").order(created_at: :desc)
    else
      @sql_order_his = SqlOrder.all.where("user_id=?",current_user.id).order(created_at: :desc).where("created_at >= current_date-7")
    end
  end

  def auditor_succeed
    sql_order = SqlOrder.find(params[:id])
    if sql_order.auditor == nil && sql_order.status == 'ready'
      sql_order.auditor = current_user.username
    end
    now = Time.now()
    if  is_deploy_time? && sql_order.schedule == nil && sql_order.status == 'ready'
      sql_order.schedule = Time.now
    else
      if ((11..13) === now.hour) && sql_order.status == 'ready' && sql_order.database.env == '生产'
        sql_order.schedule = Time.local(Time.current.year, Time.current.month, Time.current.day, 14, 00, 00)
      else
        if ((17..20) === now.hour) && sql_order.status == 'ready' && sql_order.database.env == '生产'
          sql_order.schedule = Time.local(Time.current.year, Time.current.month, Time.current.day, 21, 00, 00)
        end
      end
    end
    sql_order.save()
    sql_order.update_columns(:status=>  "audited") if sql_order.status == 'ready'
    redirect_to sql_history_path
  end

  def auditor_fail
    sql_order = SqlOrder.find(params[:id])
    if sql_order.auditor == nil && sql_order.status == 'ready'
      sql_order.auditor = current_user.username
    end
    sql_order.save()
    sql_order.update_columns(:status=>  "vetoed") if sql_order.status == 'ready'
    redirect_to sql_history_path
  end

  def execute_now
    sql_order = SqlOrder.find(params[:id])
    sql_order.update_columns(:schedule=> Time.now) if sql_order.status == 'audited'
    redirect_to sql_history_path
  end

  def cancel
    sql_order = SqlOrder.find(params[:id])
    sql_order.update_columns(:status=>  "cancelled") if sql_order.status == 'ready' or sql_order.status == 'audited' or sql_order.status == 'inqueue'
    redirect_to sql_history_path
  end

  def show_report
    sql_history = SqlContent.find(params[:id])
    if sql_history.sql_order.status == 'ready'
      if sql_history.report == nil
        report = sql_history.script
        report = report.gsub("\n", '<br>') if report
        render :text => report
      else
        info = sql_history.report + "\n" + '------------------------SQL明细如下----------------------------' + "\n" +sql_history.script
        info = info.gsub("\n", '<br>') if info
        render :text => info
      end
    else
      report = sql_history.report
      report = report.gsub("\n", '<br>') if report
      render :text => report
    end

  end
end
